<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item :label="$t('report.site.name')" prop="name">
        <el-input
          v-model="queryParams.stationName"
          :placeholder="$t('report.site.namePlaceholder')"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('report.site.reportDate')" prop="name">
        <el-date-picker ref="datePicker" v-model="chartDateArea" type="daterange"
                 :range-separator="$t('common.to')" :start-placeholder="$t('common.startDate')" :clearable="false" end-placeholder="$t('common.endDate')"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{$t('common.search')}}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{$t('common.reset')}}</el-button>
      </el-form-item>
    </el-form>
    <div style="width: 100%;" v-loading="chartDataLoading" :element-loading-text="$t('common.loading')" >
      <line-chart :chart-data="chartData" style="width: 100%;"></line-chart>
    </div>
  </div>
</template>

<script>
import lineChart from './LineChart'
import { municipalElectricityTrendData } from "@/api/ems/esReport";
export default {
  name: "electricityAnalysis",
  components:{lineChart},
  dicts:['report_chart_type','report_chart_view_position'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      deviceReportChartList: [],
      chartDateArea:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      chartDataLoading: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type:2,
        stationName: null,
        startDate:null , 
        endDate:null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      chartData: {
        xData:[],
        totalPowerConsumption:[],
        dailyPowerConsumption:[],
        dailyElectricityUsage:[],
        dailyChargingCapacity:[]
      }
    };
  },
  created() {
    this.initDate()
    this.getList();
  },
  methods: {
    initDate(){
        //图表数据，默认查询最近30天
        const end = new Date();
        const start = new Date().getTime() - 3600 * 1000 * 24 * 30;
        this.chartDateArea = [start,end];
    },
    /** 查询统计图配置列表 */
    getList() {
      if(this.chartDateArea.length > 0) {
        this.queryParams.startDate = this.parseTime(this.chartDateArea[0],'{y}-{m}-{d}')+' 00:00:00'
        this.queryParams.endDate = this.parseTime(this.chartDateArea[1],'{y}-{m}-{d}')+' 23:59:59'
      }
      this.chartDataLoading = true;
      //重置图标数据
      this.chartData = {  xData:[],  totalPowerConsumption :[] , dailyPowerConsumption:[] ,dailyElectricityUsage:[],dailyChargingCapacity:[]}
      municipalElectricityTrendData(this.queryParams).then(response => {
        let deviceReportChartList = response.data;
        let xData = [];
        let totalPowerConsumption = [] , dailyPowerConsumption=[] ,dailyElectricityUsage=[],dailyChargingCapacity=[];
        deviceReportChartList.forEach(el=>{
          xData.push(el.label)
          totalPowerConsumption.push(el.totalPowerConsumption)
          dailyPowerConsumption.push(el.dailyPowerConsumption)
          dailyElectricityUsage.push(el.dailyElectricityUsage)
          dailyChargingCapacity.push(el.dailyChargingCapacity)
        })
        this.chartData = {
          xData,totalPowerConsumption,dailyPowerConsumption,dailyElectricityUsage,dailyChargingCapacity
        }
        this.chartDataLoading = false;
      });
    },
    //查询设备类型
    getDeviceTypeOptions(){
      deviceTypeOptions().then( res => this.deviceTypeList = res.data)
    },
    getOptionsReportConfig(deviceTypeId){
      optionsReportConfig(deviceTypeId).then( res => this.reportConfigList = res.data)
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加统计图配置";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDeviceReportChart(id).then(response => {
        this.form = response.data;
        this.deviceReportChartConfigList = response.data.deviceReportChartConfigList;
        this.open = true;
        this.title = "修改统计图配置";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.deviceReportChartConfigList = this.deviceReportChartConfigList;
          if (this.form.id != null) {
            updateDeviceReportChart(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDeviceReportChart(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除统计图配置编号为"' + ids + '"的数据项？').then(function() {
        return delDeviceReportChart(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
	/** 统计图配置序号 */
    rowDeviceReportChartConfigIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 统计图配置添加按钮操作 */
    handleAddDeviceReportChartConfig() {
      let obj = {};
      obj.deviceTypeId = null 
      obj.name = "";
      obj.flag = "";
      obj.totalFlag = "";
      obj.calculate = 'NOT';
      obj.reportFlag = "";
      this.deviceReportChartConfigList.push(obj);
    },
    /** 统计图配置删除按钮操作 */
    handleDeleteDeviceReportChartConfig() {
      if (this.checkedDeviceReportChartConfig.length == 0) {
        this.$modal.msgError("请先选择要删除的统计图配置数据");
      } else {
        const deviceReportChartConfigList = this.deviceReportChartConfigList;
        const checkedDeviceReportChartConfig = this.checkedDeviceReportChartConfig;
        this.deviceReportChartConfigList = deviceReportChartConfigList.filter(function(item) {
          return checkedDeviceReportChartConfig.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleDeviceReportChartConfigSelectionChange(selection) {
      this.checkedDeviceReportChartConfig = selection.map(item => item.index)
    },  
    /** 导出按钮操作 */
    handleExport() {
      this.download('report/deviceReportChart/export', {
        ...this.queryParams
      }, `deviceReportChart_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
